<script setup lang="ts">
import AddBtn from './components/AddBtn.vue';
import AddressItem from './components/AddressItem.vue';
import $api from '@/api'
import {ref, watch} from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
const $store=useStore(),$router=useRouter()
const addresses=ref([])
const {data}=$api.address.list()
watch(data,(_data:Array<any>) =>{
  addresses.value=_data.map(item =>{
    return {
      id:item._id,
      name:item.name,
      mobile:item.mobile,
      city:item.formatted_address.split(' ')[0],
      detail:item.address,
      isDefault:item.is_default,
      _checked:false
    }
  })
  const address=$store.getters['user/getAddress']
  if(address){
    addresses.value.map(item =>{
      if(item.id==address.id){
        item._checked=true
      }else{
        item._checked=false
      }
    })
  }else{
    addresses.value.map(item =>{
      if(item.isDefault){
        item._checked=true
      }else{
        item._checked=false
      }
    })
  }
})
//点击地址
function clickAddress(item) {
  addresses.value.map(val =>val._checked=false)
  item._checked=true
  $store.commit('user/setAddress',item)
  $router.back()
}
</script>

<template>
  <div
    w:flex="~ col nowrap"
    w:align="items-center"
  >
    <div v-for="(item,idx) in addresses"
      w:flex="~ nowrap"
      w:align="items-center"
      w:justify="between"
      w:w="full"
      w:p="4"
    >
      <div class="iconfont icon-check-on" v-if="item._checked" @click="clickAddress(item)"
        w:text="4xl red-500"
        w:m="x-4"
      ></div>
      <div class="iconfont icon-check-off" v-else @click="clickAddress(item)"
        w:text="4xl"
        w:m="x-4"
      ></div>
      <AddressItem :key="item.id" :address="item" />
    </div>
    <AddBtn @click.native="$router.push('/settings/addressedit')" />
  </div>
</template>

<style scoped lang="scss">

</style>

<route>
{
  meta: {
    title: '选择地址',
    auth: true
  }
}
</route>